/**
 * Created by Administrator on 2015/1/25.
 */
var utils = require('./utils');
var commands = new Array();
var message = require('./message')
var Message = require('./message').Message;
var logger = require('./logger');
var MongoCollection = require('./config').MongoCollection;
var MongoBase = require('./mongoBase');


exports.allCommand = function () {
    return utils.processEjsTemplate("help", {commands: commands})
};

exports.execute = function (jsonParam) {
    var input = jsonParam['Content'];
    var preCheck = this.preCheck(jsonParam);
    if (preCheck != 1) {
        return preCheck;
    }
    logger.debug("input :" + input);
    for (var i = 0; i < commands.length; i++) {
        var command = commands[i];
        var check = command.command || command.text;
        if (input && input.indexOf(check) == 0) {
            var check = command.check(input);
            if (check == 1) {
                return command.callback(jsonParam);
            } else {
                var result = Message.COMMAND_HELP + command.regexStr;
                if (command.example) {
                    result += "\n比如：" + command.example
                }
                return result;
            }
        }
    }
    return this.allCommand();
}

exports.register = function (command) {
    commands.push(command);
}

var checkCommand = function (command) {

}

exports.preCheck = function (jsonParam) {
    var input = jsonParam['Content'];
    var nickNameCommand = require('./ghost-command').nickNameCommand;
    if (input.indexOf(nickNameCommand.command) > -1) {
        return 1;
    }
    var userOpenId = jsonParam['FromUserName'];
    var user = MongoBase.findOneSync(MongoCollection.USERS, {userOpenId: userOpenId});
    if (user == null) {
        return message.paraseMsg(Message.SHOULD_SET_NICKNAME, [nickNameCommand.regexStr]);
    } else {
        return 1;
    }
}


exports.getCommand = function (query) {
    for (var i = 0; i < commands.length; i++) {
        var command = commands[i];
        if (command.command == query) {
            return command;
        }
    }
    return null;
}